<?php
/**
 * User: Hufeng
 * Date: 2017/12/04 17:51
 * Desc: TRADE 支付SERVER
 */
namespace App\Controller;

use App\Model\OrderModel;
use App\Model\UserAssetsModel;
use App\Model\UserModel;
use Omnipay\Omnipay;

class Pay extends Base {
    /*余额支付*/
    public function moneyPay(){
        return;
    }
    //验证用户安全密码
    protected function checkSafePwd($uid){
        return;
    }

    /*app支付*/
    //支付宝支付签名
    public function aliPaySign(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'amount'=>array('msg'=>'amount参数异常','type'=>'float'),
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return $this->fjson($this->outData);
        }

        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        if(!$uid){
            return $this->fjson(['code'=>1,'msg'=>'账号异常，请联系客服人员']);
        }
        $orderNo = $this->buildOrderNo();
        $needPayMoney = $this->param['amount'];
        if($needPayMoney <= 0){
            return json_encode(['result'=>false,'msg'=>'待支付金额不能为0']);
        }
        $oInData = [
            'uid'=>$uid,
            'order_no'=>$orderNo,
            'order_type'=>ORDER_TYPE_CHARGE,
            'pay_money'=>$needPayMoney,
            'pay_type'=>ORDER_ALI_PAY,
            'addtime'=>$this->timeNow
        ];
        $orderModel = new OrderModel();
        $orderModel->insertData($oInData);

        $totalFee = $needPayMoney;
        $subject = '会员充值';

        $_GET = $_POST = [];
        $alipayConf = $this->getConf('business','alipay');
        $gateway = Omnipay::create('Alipay_AopApp');
        $gateway->setSignType($alipayConf['sign_type']); // RSA/RSA2/MD5
        $gateway->setAppId($alipayConf['appid']);
        $gateway->setPrivateKey($alipayConf['private_key']);
        $gateway->setAlipayPublicKey($alipayConf['alipay_public_key']);
        $gateway->setNotifyUrl($alipayConf['notify_url']);
        $request = $gateway->purchase();
        $request->setBizContent([
            'subject'      => $subject,
            'out_trade_no' => $orderNo,
            'total_amount' => $totalFee,
            'product_code' => 'QUICK_MSECURITY_PAY',
        ]);
        $response = $request->send();
        $paramStr = $response->getOrderString();
        $this->outData['data'] = $paramStr;
        $this->outData['orderNo'] = $orderNo;
        return json_encode($this->outData);
    }
    //微信支付签名
    public function wxPaySign(){
        $needParam = array(
            'openId'=>array('msg'=>'openId参数异常','type'=>'str'),
            'amount'=>array('msg'=>'amount参数异常','type'=>'float'),
        );
        $this->regArguments($needParam,$this->param);
        if($this->outData['code']){
            return json_encode($this->outData);
        }
        $uModel = new UserModel();
        $uid = $uModel->getUidByOpenId($this->param['openId']);
        $orderNo = $this->buildOrderNo();
        $needPayMoney = $this->param['amount'];
        if($needPayMoney <= 0){
            return json_encode(['result'=>false,'msg'=>'待支付金额不能为0']);
        }
        $oInData = [
            'uid'=>$uid,
            'order_no'=>$orderNo,
            'order_type'=>ORDER_TYPE_CHARGE,
            'pay_money'=>$needPayMoney,
            'pay_type'=>ORDER_ALI_PAY,
            'addtime'=>$this->timeNow
        ];
        $orderModel = new OrderModel();
        $orderModel->insertData($oInData);

        $totalFee = $needPayMoney*100;
        $subject = '会员充值';
        $body = '会员充值';
        require_once(BASEDIR.'/vendor/wxpay/lib/WxPay.Api.php');
        require_once(BASEDIR.'/vendor/wxpay/example/WxPay.NativePay.php');

        $notify = new \NativePay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetAttach($subject);
        $input->SetOut_trade_no(\WxPayConfig::MCHID.$orderNo);
        $input->SetTotal_fee($totalFee);
        $input->SetTime_start(date("YmdHis"));
        $etime = time() + 43200;
        $input->SetTime_expire(date("YmdHis", $etime));
        $input->SetGoods_tag($subject);
        $input->SetTrade_type("NATIVE");
        $input->SetProduct_id($orderNo);
        $result = $notify->GetPayUrl($input);

        $data = [];
        $data['appid'] = $result['appid'];
        $data['prepayid'] = $result['prepay_id'];
        $data['partnerid'] = $result['mch_id'];
        $data['noncestr'] = md5(rand(100114,99999999));
        $data['timestamp'] = $etime;
        $data['package'] = 'Sign=WXPay';
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        $wxPay = new \WxPayDataBase();
        $wxPay->FromXml($xml);
        $sign = $wxPay->MakeSign();
        $data['sign'] = $sign;
        $data['orderNo'] = $orderNo;
        $this->outData['data'] = $data;
        return json_encode($this->outData);
    }

    /*支付回调*/
    //支付宝异步回调
    public function aliPayAsync(){
        $tmpPost = $_POST;
        $_GET = $_POST = [];
        $alipayConf = $this->getConf('business','alipay');
        $gateway = Omnipay::create('Alipay_AopApp');
        $gateway->setSignType($alipayConf['sign_type']); // RSA/RSA2/MD5
        $gateway->setAppId($alipayConf['appid']);
        $gateway->setPrivateKey($alipayConf['private_key']);
        $gateway->setAlipayPublicKey($alipayConf['alipay_public_key']);
        $gateway->setNotifyUrl($alipayConf['notify_url']);
        $request = $gateway->completePurchase();
        $request->setParams($tmpPost);
        try {
            $response = $request->send();
            if($response->isPaid()){
                //商户订单号
                $orderNo = $this->param['out_trade_no'];
                //支付宝交易号
                $trade_no = $this->param['trade_no'];
                $this->dealOrder($orderNo,ORDER_ALI_PAY,$trade_no);
                return 'success';
            }else{
                return 'fail';
            }
        } catch (Exception $e) {
            return 'fail';
        }
    }
    public function aliPaySync(){
        return;
    }

    //微信异步回调
    public function wxPayAsync(){
        require_once BASEDIR."/vendor/wxpay/lib/WxPay.Api.php";
        require_once BASEDIR."/vendor/wxpay/lib/WxPay.Notify.php";
        require_once BASEDIR."/vendor/wxpay/lib/WxPay.Config.php";

        $xml = $GLOBALS;
        $xmlArr = \WxPayResults::Init($xml);
        if($xmlArr['appid'] == \WxPayConfig::APPID && $xmlArr['mch_id'] == \WxPayConfig::MCHID && ($xmlArr['result_code'] == 'SUCCESS' || $xmlArr['return_code'] == 'SUCCESS')){
            //商户订单号
            $orderNo = str_replace(\WxPayConfig::MCHID,'',$xmlArr['out_trade_no']);
            //微信交易号
            $trade_no = $xmlArr['transaction_id'];
            $this->dealOrder($orderNo,ORDER_WX_PAY,$trade_no);
        }
    }
    public function wxPaySync(){
        return;
    }

    //处理订单
    protected function dealOrder($orderNo,$payType,$tradeNo){
        $payTypeArr = $this->getConf('business','paytype');
        $payNameStr = $payTypeArr[$payType];
        $orderModel = new OrderModel();
        $orderRes = $orderModel->findData(['order_no'=>$orderNo,'status'=>1],['id','order_type','uid','pay_money']);
        $orderModel->editData(['id'=>$orderRes['id']],['status'=>2,'paytime'=>date('Y-m-d H:i:s'),'pay_type'=>$payType,'out_trade_no'=>$tradeNo]);
        if($orderRes['order_type']==ORDER_TYPE_CHARGE){
            //充值余额
            $uaModel = new UserAssetsModel();
            $uaModel->addAssets($orderRes['uid'],$orderRes['pay_money']*100000,BALANCE_MONEY,BALANCE_ENABLE,$payNameStr);
        }
    }
}
